import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import React, { useState, useCallback, useEffect, useMemo } from 'react';
import { useRequest } from '@umijs/hooks';
import { Button, Steps, message } from 'antd';
import styles from './index.less';
import moment from 'moment';
import router from 'umi/router';

import {
  selectCityInfo,
  createUnderchargeAccident,
  getPkgAccidentDetail,
  updateUnderchargeAccident,
  getUserServiceCity,
  turnToDamageOrLost
} from './service';
import {
  Const
} from '../Const';

import AuthComponent from '@/components/Authorized/AuthComponent';
import Step1 from './components/Step1';
import Step2 from './components/Step2';
import Step3 from './components/Step3';
import Step4 from './components/Step4';

const { Step } = Steps;

class PrivateData {
  static stepArr = ['旅客信息', '行李信息', '补充信息', '完成'];
  static stepComponents = [Step1, Step2, Step3, Step4];
  static saveData = {};
}

const AddEditIncident = props => {

  const { location: { state } } = props;

  const [stepCurrent, setStepCurrent] = useState(0); // step值
  const [itemData, setItemData] = useState({});
  const [accidentId, setAccidentId] = useState(''); // 事故单ID

  const [userServiceCity, setUserServiceCity] = useState(''); // 用户默认服务航站

  // 获取详情
  const { run: runGetPkgAccidentDetail } = useRequest(params => getPkgAccidentDetail(params), {
    manual: true,
    onSuccess (res) {
      console.log(res, '获取详情');
      setItemData(res.pkgAccidentDetailInfoVo || {});
    }
  });

  // 获取登录用户所属航站
  const { run: runGetUserServiceCity } = useRequest(getUserServiceCity, {
    manual: true,
    onSuccess (res) {
      console.log(res, '获取登录用户所属航站');
      let data = res.serviceCity || '';
      setUserServiceCity(data);
    }
  });

  // 创建事故单
  const { run: runCreateUnderchargeAccident, loading: addLoading } = useRequest(data => createUnderchargeAccident(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '创建事故单');
      let arr = (res || '').split(',');
      if (arr && arr.length >= 1) {
        setAccidentId(arr[0]);
        setStepCurrent(3);
      }
    }
  });

  // 转破损、内物缺失
  const { run: runTurnToDamageOrLost, loading: turnLoading } = useRequest(data => turnToDamageOrLost(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '转破损、内物缺失');
      setAccidentId(res);
      setStepCurrent(3);
    }
  });

  // 编辑事故单
  const { run: runUpdateUnderchargeAccident, loading: editLoading } = useRequest(data => updateUnderchargeAccident(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '编辑事故单');
      setAccidentId(res);
      setStepCurrent(3);
    }
  });

  // 航站下拉列表
  const { data: selectCityData = [] } = useRequest(selectCityInfo);

  useEffect(() => {
    runGetUserServiceCity();
    return () => {
      PrivateData.saveData = {};
    }
  }, []);

  useEffect(() => {
    console.log(state);
    if (state.type === 'edit' && state.accidentId) {
      runGetPkgAccidentDetail({
        accidentId: state.accidentId || ''
      });
    }
  }, [state]);

  // 防止重复提交
  const saveFormStatus = useMemo(() => {
    return (addLoading || turnLoading || editLoading);
  }, [addLoading, turnLoading, editLoading]);

  // 上一步
  const prevStep = useCallback(() => {
    if (stepCurrent <= 0) {
      router.goBack();
    } else {
      setStepCurrent(stepCurrent - 1);
    }
  }, [stepCurrent]);
  // 下一步
  const nextStep = useCallback((obj) => {
    if (stepCurrent >= PrivateData.stepArr.length - 1) return;
    PrivateData.saveData = {
      ...PrivateData.saveData,
      ...obj
    }
    if (stepCurrent >= 2) {
      if (saveFormStatus) {
        message.warning('请勿重复提交');
        return;
      }
      const isAuth = AuthComponent.getAuth(Const.permissionsType.get(+state.ownerType) + '.changeAllIncident') ? 1 : 0;
      if (state.type === 'add') {
        let saveData = {
          ...PrivateData.saveData,
          accidentType: state.ownerType,
          operateType: 1, // 0草稿 1提交
        }
        saveData.flightNo = saveData.pkgFlightNo || '';
        saveData.flightDate = saveData.pkgFlightDate || '';
        runCreateUnderchargeAccident(saveData);
      } else {
        if (state?.isTurn) {
          runTurnToDamageOrLost({
            ...PrivateData.saveData,
            accidentType: state.ownerType,
            operateType: 1, // 0草稿 1提交
            accidentId: state.accidentId || ''
          });
        } else {
          runUpdateUnderchargeAccident({
            ...PrivateData.saveData,
            accidentType: state.ownerType,
            operateType: 1, // 0草稿 1提交
            accidentId: state.accidentId || '',
            isAuth
          });
        }
      }
    } else {
      setStepCurrent(stepCurrent + 1);
    }
  }, [stepCurrent, state, saveFormStatus]);

  return (
    <div className={styles.addEditIncident}>
      {/* 步骤进度条 */}
      <div className={styles.stepBox}>
        <Steps current={stepCurrent}>
          {PrivateData.stepArr.map((item, index) => (
            <Step title={item} key={index} />
          ))}
        </Steps>
      </div>
      {/* 步骤form内容 */}
      <div className={styles.contentBox}>
        {PrivateData.stepComponents.map((item, index) => {
          const StepItem = item;
          if (index === 0) {
            return (
              <StepItem
                key={index}
                className={stepCurrent === index ? '' : styles.hideBox}
                itemData={state.type === 'add' ? (state.itemData[0] || {}) : itemData}
                isHave={state.isHave}
                selectCityData={selectCityData}
                prevStep={prevStep}
                nextStep={nextStep}
                stepCurrent={stepCurrent}
                ownerType={state.ownerType}>
              </StepItem>
            )
          }
          return (
            <StepItem
              key={index}
              type={state.type}
              className={stepCurrent === index ? '' : styles.hideBox}
              itemData={state.type === 'add' ? (state.itemData[0] || {}) : itemData}
              prevStep={prevStep}
              nextStep={nextStep}
              selectCityData={selectCityData}
              stepCurrent={stepCurrent}
              accidentId={accidentId}
              userServiceCity={userServiceCity}
              isFromQuickRetrieval={state?.isFromQuickRetrieval || ''}
              ownerType={state.ownerType}>
            </StepItem>
          )
        })}
      </div>
    </div>
  )
}

export default AddEditIncident;
